package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhentao.api.schedule.ScheduleClientApi;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.TaskTypeEnum;
import com.zhentao.model.schedule.dto.TaskDto;
import com.zhentao.model.wemedia.pojo.WmNews;
import com.zhentao.service.WmNewsAutoScanService;
import com.zhentao.service.WmNewsTaskService;
import com.zhentao.utils.common.ProtostuffUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private ScheduleClientApi scheduleClientApi;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;


    //怎么调用   调用一次取出一个数据，并把list里面得数据给删除
    //第二次调用   第三次调用  。。。
    //每调用一次取出一次数据 进行自动审核   --定时任务 1s一次

    @Override
    @Async//开启异步调用
    public void addNewsToTask(Integer id, Date publishTime) {
        //添加数据库到任务表
        //2.要执行的数据添加list里面，未来5分钟执行的添加到zSet里面
        log.info("添加任务到延迟服务中---------begin");
        TaskDto taskDto = new TaskDto();
        taskDto.setTaskType(TaskTypeEnum.REMOTEERROR.getTaskType());
        taskDto.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        taskDto.setExecuteTime(publishTime.getTime());
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        taskDto.setParameters(ProtostuffUtil.serialize(wmNews));
        scheduleClientApi.addTask(taskDto);
        log.info("添加任务到延迟服务中---------end");
    }

    /**
     * 消费任务，审核文章,每秒中拉取任务
     */
    @Override
    @Scheduled(fixedDelay = 1000)
    public void scanNewsByTask() {

        log.info("消费任务，审核文章");
        ResponseResult responseResult = scheduleClientApi.poll(TaskTypeEnum.REMOTEERROR.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (responseResult.getCode() == 200 && responseResult.getData() != null) {
            //消费任务
            TaskDto taskDto = JSON.parseObject(JSON.toJSONString(responseResult.getData()), TaskDto.class);
            WmNews wmNews = ProtostuffUtil.deserialize(taskDto.getParameters(), WmNews.class);
            wmNewsAutoScanService.autoScanWnMews(wmNews.getId());
        }
    }


}